// pages/createCard/createCard.js
import request from '../../utils/config.js';
import formatDate from '../../utils/util.js';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ossImgUrL: 'https://winhc.oss-cn-shanghai.aliyuncs.com/xcx/',
    animationData: {},
    errorMsg: "",
    showImageList: new Array(),
    bgImage: "",
    userName: "",
    userPhone: "",
    companyName: "",
    userType: '0',//0：普通 1：律师
    dutyName: "",
    emailName: "",
    fieldList: new Array(),
    hideFiled: true,
    animationFieldData: false,
    advfiledList: [
      { name: "合同纠纷", slt: false },
      { name: "债权债务", slt: false },
      { name: "房产纠纷", slt: false },
      { name: "建设工程", slt: false },
      { name: "知识产权", slt: false },
      { name: "交通事故", slt: false },
      { name: "婚姻家庭", slt: false },
      { name: "劳动纠纷", slt: false },
      { name: "金融证券", slt: false },
      { name: "刑事行政", slt: false },
      { name: "海事海商", slt: false },
      { name: "涉外纠纷", slt: false },
      { name: "公司企业", slt: false },
      { name: "其他", slt: false }
    ],
    moreName: "",
    addressData: "",
    latitude: "",
    longitude: "",
    showNameDel: "none",
    showPhoneDel: "none",
    showYzmView: "none",
    showYzmDel: "none",
    showCompanyDel: "none",
    showDutyDel: "none",
    showEmailDel: "none",
    showPicTap: "block",
    nameplaceholder: '请输入你的姓名',
    imgUrlSub: '',
    isFouse: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log("获取上一页面的参数=", options.id)
    // console.log(app.globalData.userInfo)
    if (app.globalData.persionalInfo) {
      var addressName = app.globalData.persionalInfo.address;
      if (!app.globalData.persionalInfo.address) {
        addressName = "未选择位置，请选择您的位置信息";
      }
      let tempImgList = new Array;
      if (app.globalData.persionalInfo.images) {
        tempImgList = JSON.parse(app.globalData.persionalInfo.images);
        let tempArray = tempImgList.length;
        // console.log('图片张数=', tempArray)
        if (tempArray == "9") {
          this.setData({
            showPicTap: "none"
          })
        }
      }
      let userType = '0';
      let fieldList = new Array();
      if (app.globalData.persionalInfo.lawfirmName.indexOf('律师') != -1 || app.globalData.persionalInfo.lawfirmName.indexOf('律所') != -1 || app.globalData.persionalInfo.title.indexOf('律师') != -1) {
        userType = '1';
        if (app.globalData.persionalInfo.advField) {
          fieldList = app.globalData.persionalInfo.advField.split(',');
        } else {
          fieldList = new Array();
        }
      }
      this.setData({
        bgImage: app.globalData.persionalInfo.avatarUrl,
        userName: app.globalData.persionalInfo.userName,
        userPhone: app.globalData.persionalInfo.mobileNo,
        companyName: app.globalData.persionalInfo.lawfirmName,
        dutyName: app.globalData.persionalInfo.title,
        emailName: app.globalData.persionalInfo.email,
        moreName: app.globalData.persionalInfo.moreExt,
        latitude: app.globalData.persionalInfo.latitude,
        longitude: app.globalData.persionalInfo.longitude,
        userType: userType,
        fieldList: fieldList,
        showImageList: tempImgList,
        addressData: addressName
      });
    }
  },

  //点击显示擅长领域
  showFiled: function () {
    // console.log(this.data.fieldList)
    let value = this.data.fieldList;
    let temFieldList = this.data.advfiledList;
    
    if (value.length > 0) {
      for (let i = 0; i < value.length; i++) {
        // console.log('循环了已选值', value[i])
        for (let j = 0; j < temFieldList.length; j++) {
          // console.log('循环列表', temFieldList[j].name)
          if ( value[i] == temFieldList[j].name) {
            temFieldList[j].slt = true;
            temFieldList[j].imgSlt = true;
          }
        }
      }
    }
    this.setData({
      hideFiled: false,
      isFouse: false,
      animationFieldData: true,
      advfiledList: temFieldList
    });
    // var animation = wx.createAnimation({
    //   duration: 50,
    //   timingFunction: 'ease',
    // })
    // this.animation = animation
    // animation.scale(1,1).step()
    // this.setData({
    //   animationFieldData: animation.export()
    // });
  },

  //点击擅长
  selectItems: function (e) {
    console.log(e)
    let index = e.target.dataset.key;
    let temFieldList = this.data.advfiledList;
    if (temFieldList[index].slt) {
      temFieldList[index].slt = false;
      temFieldList[index].imgSlt = false;
    } else {
      let tempIndex = 0;
      temFieldList.forEach(function (e) {
        if (e.slt) {
          tempIndex++
        }
      });
      if (tempIndex < 4) {
        temFieldList[index].slt = true;
        temFieldList[index].imgSlt = true;
      }
    }
    this.setData({
      advfiledList: temFieldList
    });
  },

  //取消擅长领域
  cancleField: function () {
    // var animation = wx.createAnimation({
    //   duration: 50,
    //   timingFunction: 'ease',
    // })
    // this.animation = animation
    // animation.scale(0,0).step()
    this.setData({
      hideFiled: true,
      isFouse: true,
      animationFieldData: false
    });
  },

  //确定擅长领域
  confirmField: function () {
    let temFieldList = this.data.advfiledList;
    let filedList = new Array();
    temFieldList.forEach(function (e) {
      if (e.slt) {
        filedList.push(e.name);
      }
    });
    console.log("filedList=", filedList)
    // if (filedList.length > 0){
    // var animation = wx.createAnimation({
    //   duration: 500,
    //   timingFunction: 'ease',
    // })
    // this.animation = animation
    // animation.scale(0,0).step()
    this.setData({
      fieldList: filedList,
      hideFiled: true,
      isFouse: true,
      animationFieldData: false
    });
    // }
  },

  // 点击获取本地照片
  getNativePic: function () {
    var _this = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        console.log("获取照片资源返回结果=", res);
        var tempFilePaths = res.tempFilePaths[0];
        let bodyInfo = {
          path: tempFilePaths
        }
        request.requestUploadImg('pictures', bodyInfo, (res) => {
          console.log("上传图片成功=", res);
          _this.setData({
            bgImage: res.data
          });
        }, (res) => {
          console.log("上传图片失败=", res);
        })
      }
    })
  },

  //聚焦姓名输入框
  nameFocus: function (e) {
    console.log("聚焦e=", e);
    this.setData({
      showNameDel: "block",
      nameplaceholder: ''
    });
  },

  //失焦姓名输入框
  nameBlur: function (e) {
    console.log("失焦e=", e);
    this.setData({
      showNameDel: "none",
      nameplaceholder: '请输入你的姓名'
    });
  },

  //删除姓名
  delNameTap: function () {
    this.setData({
      userName: ""
    });
  },

  //姓名触发
  changeName: function (e) {
    this.setData({
      userName: e.detail.value
    });
  },

  //聚焦手机号输入框
  phoneFocus: function (e) {
    // console.log("聚焦e=", e);
    this.setData({
      showPhoneDel: "block"
    });
  },

  //失焦手机号输入框
  phoneBlur: function (e) {
    // console.log("聚焦e=", e);
    this.setData({
      showPhoneDel: "none"
    });
  },

  //删除手机号
  delPhoneTap: function (e) {
    // console.log("删除手机号=",e)
    this.setData({
      showSltTiew: false,
      userPhone: ""
    });
  },

  //手机号触发
  changePhone: function (e) {
    // console.log("手机号触发=", e);
    if (String(e.detail.value).length == 11) {
      this.setData({
        userPhone: e.detail.value,
        showSltTiew: true
      });
    } else {
      this.setData({
        userPhone: e.detail.value,
        showSltTiew: false
      });
    }
  },

  //更换手机号
  changeMobileNo: function () {
    console.log('跳了')
    wx.navigateTo({
      url: '../telPhone/telPhone',
    })
  },

  //聚焦验证码输入框
  yzmFocus: function (e) {
    // console.log("聚焦e=",e);
    this.setData({
      showYzmDel: "block"
    });
  },

  //失焦验证输入框
  yzmBlur: function (e) {
    // console.log("失焦e=", e);
    this.setData({
      showYzmDel: "none"
    });
  },

  //删除验证码
  delYzmTap: function () {
    this.setData({
      yamNo: ""
    });
  },

  //验证码触发
  yzmAuth: function (e) {
    this.setData({
      yamNo: e.detail.value
    });
  },

  //聚焦公司名称输入框
  companyFocus: function (e) {
    // console.log("聚焦e=",e);
    this.setData({
      showCompanyDel: "block"
    });
  },

  //失焦公司名称输入框
  companyBlur: function (e) {
    // console.log("失焦e=", e);
    this.setData({
      showCompanyDel: "none"
    });
  },

  //删除公司名称
  delCompanyTap: function () {
    this.setData({
      companyName: ""
    });
  },

  //公司名称触发
  companyTap: function (e) {
    this.setData({
      companyName: e.detail.value
    });
  },

  //聚焦职务输入框
  dutyFocus: function (e) {
    // console.log("聚焦e=",e);
    this.setData({
      showDutyDel: "block"
    });
  },

  //失焦职务输入框
  dutyBlur: function (e) {
    // console.log("失焦e=", e);
    this.setData({
      showDutyDel: "none"
    });
  },

  //删除职务
  delDutyTap: function () {
    this.setData({
      dutyName: ""
    });
  },

  //职务触发
  dutyTap: function (e) {
    let userType = this.data.userType;
    let companyName = this.data.companyName;
    if (e.detail.value.indexOf('律师') != -1 || this.data.companyName.indexOf('律所') != -1 || this.data.companyName.indexOf('律师') != -1) {
      userType = '1';
    } else {
      userType = '0';
    }
    this.setData({
      dutyName: e.detail.value,
      userType: userType
    });
  },

  //公司名称触发
  companyTap: function (e) {
    let userType = this.data.userType;
    let dutyName = this.data.dutyName;
    if (e.detail.value.indexOf('律所') != -1 || e.detail.value.indexOf('律师') != -1 || this.data.dutyName.indexOf('律师') != -1) {
      userType = '1';
    } else {
      userType = '0';
    }
    this.setData({
      companyName: e.detail.value,
      userType: userType
    });
  },

  //聚焦邮箱输入框
  emailFocus: function (e) {
    // console.log("聚焦e=",e);
    this.setData({
      showEmailDel: "block"
    });
  },

  //失焦邮箱输入框
  emailBlur: function (e) {
    console.log("失焦e=", e.detail.value);
    if (!e.detail.value) {
      this.setData({
        showEmailDel: "none"
      });
    } else {
      if (formatDate.fChkMail(e.detail.value)) {
        this.setData({
          showEmailDel: "none"
        });
      } else {
        this.showErrorMsg("邮箱格式不正确");
      }
    }
  },

  //删除邮箱
  delEmailTap: function () {
    this.setData({
      emailName: ""
    });
  },

  //邮箱触发
  emailTap: function (e) {
    this.setData({
      emailName: e.detail.value
    });
  },

  //绑定更多数据
  moreTap: function (e) {
    this.setData({
      moreName: e.detail.value
    });
  },

  //开始创建卡片
  createCardNow: function () {
    if (!this.data.userName) {
      this.showErrorMsg("请输入姓名");
    } else if (!this.data.userPhone) {
      this.showErrorMsg("请输入手机号");
    } else if (!this.data.companyName) {
      this.showErrorMsg("请输入公司名称");
    } else if (!this.data.dutyName) {
      this.showErrorMsg("请输入职务名称");
    } else {
      if (this.data.emailName) {
        if (!formatDate.fChkMail(this.data.emailName)) {
          this.showErrorMsg("请输入正确的邮箱");
        } else {
          //开始保存本地数据
          if (this.data.addressData == '未选择位置，请选择您的位置信息') {
            this.data.addressData = "";
          }

          console.log("上传图片信息=", this.data.showImageList)
          let fieldList = "";
          if (this.data.fieldList.length > 0) {
            fieldList = this.data.fieldList.join();
          }
          let bodyInfo = {
            "openid": app.globalData.openid,
            "avatarUrl": this.data.bgImage,
            "userName": this.data.userName,
            "mobileNo": this.data.userPhone,
            'verifyStatus': app.globalData.persionalInfo.verifyStatus,
            'lawfirmName': this.data.companyName,
            'title': this.data.dutyName,
            'email': this.data.emailName,
            'images': JSON.stringify(this.data.showImageList),
            'moreExt': this.data.moreName,
            'address': this.data.addressData,
            latitude: this.data.latitude,
            longitude: this.data.longitude,
            'userType': this.data.userType,
            'status': '0',
            'advField': fieldList
          };
          request.post_api("modifyUserInfo", bodyInfo, (res) => {
            wx.hideLoading();
            console.log("用户编辑信息成功=", res)
            if (res.data.isSuccess == 'T') {
              //保存数据
              app.globalData.persionalInfo = JSON.parse(res.data.body);
              wx.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 1500
              })
              wx.navigateBack();
            }
          }, (res) => {
            wx.hideLoading();
            console.log("用户编辑信息失败=", res)
          });
        }
      } else {
        //开始保存本地数据
        if (this.data.addressData == '未选择位置，请选择您的位置信息') {
          this.data.addressData = "";
        }

        console.log("上传图片信息=", this.data.showImageList)
        let fieldList = "";
        if (this.data.fieldList.length > 0) {
          fieldList = this.data.fieldList.join();
        }
        let bodyInfo = {
          "openid": app.globalData.openid,
          "avatarUrl": this.data.bgImage,
          "userName": this.data.userName,
          "mobileNo": this.data.userPhone,
          'verifyStatus': app.globalData.persionalInfo.verifyStatus,
          'lawfirmName': this.data.companyName,
          'title': this.data.dutyName,
          'email': this.data.emailName,
          'images': JSON.stringify(this.data.showImageList),
          'moreExt': this.data.moreName,
          'address': this.data.addressData,
          'latitude': this.data.latitude,
          'userType': this.data.userType,
          'status': '0',
          'advField': fieldList,
          "longitude": this.data.longitude
        };
        request.post_api("modifyUserInfo", bodyInfo, (res) => {
          wx.hideLoading();
          console.log("用户编辑信息成功=", res)
          if (res.data.isSuccess == 'T') {
            //保存数据
            app.globalData.persionalInfo = JSON.parse(res.data.body);
            wx.showToast({
              title: '提交成功',
              icon: 'success',
              duration: 1500
            })
            wx.navigateBack();
          }
        }, (res) => {
          wx.hideLoading();
          console.log("用户编辑信息失败=", res)
        });
      }
    }
  },

  //errorMsg显示
  showErrorMsg: function (msg) {
    this.setData({
      errorMsg: msg
    });
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })
    this.animation = animation
    animation.translateY(26).step()
    this.setData({
      animationData: animation.export()
    })
    setTimeout(function () {
      animation.translateY(-26).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 2000)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.persionalInfo) {
      this.setData({
        userPhone: app.globalData.persionalInfo.mobileNo
      });
    }
  },

  //选择照片
  chooseImage: function () {
    var len = 9 - (this.data.showImageList).length;
    var _this = this;
    wx.chooseImage({
      count: len, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.log("选择照片=", res);
        var tempArray = _this.data.showImageList;
        tempArray = tempArray.concat(tempFilePaths);
        // console.log("照片几张=", tempArray.length);
        if (tempArray.length == 9) {
          _this.setData({
            showPicTap: "none"
          });
        }
        //开始上传图片
        _this.startUploadImage(tempFilePaths, _this, 0);
      }
    })
  },

  //开始上传图片
  startUploadImage: (flieList, _that, index) => {
    wx.showLoading({
      title: '正在上传...',
    });
    console.log("index=", index);
    console.log("flieList=", flieList.length);
    if (index > flieList.length - 1) {
      wx.hideLoading();
      wx.showToast({
        title: '上传成功',
        icon: 'success',
        duration: 1500
      })
      return;
    } else {
      let path = flieList[index];
      let _this = _that;
      let bodyInfo = {
        path: path
      }
      request.requestUploadImg('pictures', bodyInfo, (res) => {
        console.log("上传图片成功=", res);
        var tempRealImgList = _this.data.showImageList;
        tempRealImgList.push(res.data);
        _this.setData({
          showImageList: tempRealImgList
        });
        let tempflag = index + 1;
        console.log("tempflag=" + tempflag)
        _this.startUploadImage(flieList, _this, tempflag);
      }, (res) => {
        console.log("上传图片失败=", res);
      })
    }
  },

  //删 除 oss 照 片
  delImage: function (e) {
    let tempArray = this.data.showImageList;
    let _this = this;
    if (tempArray.length > 0) {
      let index = e.target.dataset.key;
      let path = tempArray[index];
      if (typeof path != "undefined") {
        path = path.substr(43);
      }
      let bodyInfo = {
        fileName: path
      }
      request.post_api('delFiles/{fileName}', bodyInfo, (res) => {
        console.log("删除图片=", res);
        tempArray.splice(e.target.dataset.key, 1);
        _this.setData({
          showImageList: tempArray,
          showPicTap: "block"
        });
      }, (res) => {
        console.log("上传图片失败=", res);
      })
    } else {
      tempArray = new Array();
    }
  },

  //预览照片
  showImage: function (e) {
    console.log("点击预览照片", e.target.dataset.url);
    var tempUrl = e.target.dataset.url;
    wx.previewImage({
      current: tempUrl, // 当前显示图片的http链接
      urls: [tempUrl] // 需要预览的图片http链接列表
    })
  },

  //选择位置
  selectLocation: function () {
    var _this = this;
    wx.getSetting({
      success: res => {
        console.log("授权返回=", res)
        if (res.authSetting['scope.userLocation']) {
          wx.chooseLocation({
            success: function (res) {
              console.log("选择位置", res);
              _this.setData({
                addressData: res.address,
                latitude: res.latitude,
                longitude: res.longitude
              });
            },
            fail: function (res) {
              _this.globalTipMsg(_this);
            }
          });
        } else {
          _this.globalTipMsg(_this);
        }
      }
    })
  },

  //清除信息
  clearAddress: function () {
    this.setData({
      addressData: "未选择位置，请选择您的位置信息"
    });
  },

  globalTipMsg: (that) => {
    var _this = that;
    wx.showModal({
      title: '小程序需要你的允许才能正常使用',
      content: '请点击"去设置"并启用"地理位置",然后确定即可正常使用',
      confirmText: '去设置',
      confirmColor: '#35ca14',
      success: function (res) {
        if (res.confirm) {
          wx.openSetting({
            success: (res) => {
              res.authSetting = {
                "scope.userInfo": true,
                "scope.userLocation": true
              }
              //这里是授权成功之后 填写你重新获取数据的js
              wx.chooseLocation({
                success: function (res) {
                  _this.setData({
                    addressData: res.address,
                    latitude: res.latitude,
                    longitude: res.longitude
                  });
                },
                fail: function (res) {

                }
              });
            }
          })
        } else if (res.cancel) {
          wx.showModal({
            title: '微信获取位置信息失败',
            content: '请重新打开小程序，或联系客服解决(错误原因: userLocation:fail authdeny)',
            confirmText: '确定',
            confirmColor: '#35ca14',
            success: function (res) {
              if (res.confirm) {
                // 
              } else if (res.cancel) {
                //  
              }
            }
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }

})